package cn.sx.yys.blog.config.interceptor;

import cn.sx.yys.support.Consts;
import cn.sx.yys.support.ErrorCode;
import cn.sx.yys.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 权限拦截器
 *
 * @author 猿帅
 * @email 1603194187@qq.com
 * @date 2021/1/29 15:13
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行所有 OPTIONS 请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            return true;
        }

        //取出http请求头中的token
        String token = request.getHeader("Authorization");
        //判断token是否有效
        if (redisTemplate.hasKey(Consts.KEY_PRE_LOGIN + token)) {
            //刷新缓存key，重置会话有效期
            redisTemplate.expire(Consts.KEY_PRE_LOGIN + token, 30, TimeUnit.MINUTES);
            return true;
        }

        //用户未登录处理
        Map<String, Object> result = new HashMap<>(3);
        result.put("msg", ErrorCode.LoginError.getText());
        result.put("code", ErrorCode.LoginError.getCode());

        //通过response设置http请求状态码、返回json数据
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getWriter().write(JsonUtils.toJSON(result));

        return false;
    }
}
